package com.hundsun.cprs.yyt.service.rabbit.listener;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.account.service.IntegralService;
import com.hundsun.cprs.yyt.service.common.dto.ReferRelateInfo;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.service.RemoteBrokerService;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.system.enums.EnumBussinessParam;
import com.hundsun.cprs.yyt.service.system.service.BusinessParamHelper;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import com.hundsun.cprs.yyt.util.ShortUUIDGenerator;
import com.hundsun.cprs.yyt.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 处理实名消息
 * 实名之后赠送积分和给相应的推荐人赠送积分
 *
 * @author jinghn20983
 *
 */
@Component
public class IntegralChangeListener implements MessageListener {

    protected Log logger = LogFactory.getLog(IntegralChangeListener.class);

    @Autowired
    private BussinessParamService bussinessParamService;

    @Autowired
    private RemoteBrokerService remoteBrokerService;

    @Autowired
    private IntegralService integralService;

    @Autowired
    private RemoteUserService remoteUserService;


    @Override
    public void onMessage(Message message) {
        String receviedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        Map<String,String> userRealNameInfo = JSON.parseObject(new String(message.getBody()), Map.class);
        try {

            if (RoutingKeyConstants.BID_USER_REALNAME.equals(receviedRoutingKey)) {

                //用户userID
                String userId = userRealNameInfo.get("userId");

                //实名成功后赠送给本人积分100
                this.sendSelfIntegral(userId);

                //用户的推荐人实名获得50积分
                this.sendReferIntegral(userId);

            }
        } catch (ServiceCodeException e) {
            logger.warn(e.getErrorDesc());

        }catch (Exception e) {
            logger.error("实名赠送积分异常:userId："+userRealNameInfo.get("userId")+",错误原因：",e);
        }
    }

    /**
     * 实名成功后赠送给本人积分100
     * @param userId
     */
    private void sendSelfIntegral(String userId){
        int realNameAddIntegralAmount =  this.realNameAddIntegralAmount();

        if(realNameAddIntegralAmount > 0){

            //实名成功后赠送给本人积分100
            integralService.addIntegeral(Long.valueOf(userId),realNameAddIntegralAmount,ShortUUIDGenerator.generate(),"会员实名赠送[" +realNameAddIntegralAmount+"]积分");
        }

    }

    /**
     * 用户的推荐人实名获得50积分
     * @param userId
     */
    private void sendReferIntegral(String userId){

        //获取用户的上级推荐信息
        ReferRelateInfo referRelateInfo = this.getUpRefer(userId);
        if(referRelateInfo == null){
            logger.warn("该用户没有推荐人信息,会员userId："+userId);
            return ;
        }
        //被推荐人实名后，其推荐人（需要实名）获得50积分
        UserAccountDTO userInfo = remoteUserService.getUserDetailByUserId(Long.valueOf(referRelateInfo.getUpUserId()));
        if(userInfo == null){
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(),EnumBusinessCode.BUSINESS_1001.getErrorInfo());
        }

        if(StringUtil.isBlank(userInfo.getCertificateNum())){
            logger.warn("此会员的推荐人没有实名，没有获取积分的资格,会员userId" + userId + ",推荐人userId：" + referRelateInfo.getUpUserId() + "!");
            return ;
        }

        //会员的上级推荐人获得积分总数
        int realNameAddReferIntegralAmount = this.realNameAddReferIntegralAmount();

        if(realNameAddReferIntegralAmount > 0){

            //用户的推荐人实名获得50积分
            integralService.addIntegeral(Long.valueOf(userInfo.getId()),realNameAddReferIntegralAmount,ShortUUIDGenerator.generate(),"会员实名,推荐人赠送[" +realNameAddReferIntegralAmount+"]积分");
        }

    }

    /**
     * 获取用户的上级推荐信息
     * @param userId
     * @return
     */
    private ReferRelateInfo getUpRefer(String userId){
        //获取用户的上级推荐信息
        ReferRelateInfo referRelateInfo = remoteBrokerService.queryReferRelate(userId);

        return referRelateInfo;
    }
    /**
     *用户实名获得100积分
     */
    private int realNameAddIntegralAmount(){
        int integralAmount = BusinessParamHelper.getIntValue(bussinessParamService, EnumBussinessParam.REAL_NAME_ADD_INTEGRAL, null);

        return integralAmount;
    }


    /**
     *用户的推荐人实名获得50积分
     */
    private int realNameAddReferIntegralAmount(){
        int integralAmount = BusinessParamHelper.getIntValue(bussinessParamService, EnumBussinessParam.REAL_NAME_REFER_ADD_INTEGRAL, null);
        return integralAmount;
    }
}
